package com.gimi.cloud.jimi.manage.service.app.impl;

import com.gimi.cloud.jimi.common.enums.CommonEnume;
import com.gimi.cloud.jimi.common.enums.ResponseCodeEnum;
import com.gimi.cloud.jimi.common.exception.MsgException;
import com.gimi.cloud.jimi.common.utils.Page;
import com.gimi.cloud.jimi.common.utils.StringUtil;
import com.gimi.cloud.jimi.common.utils.oss.AliOSSUtil;
import com.gimi.cloud.jimi.commonService.common.JmOperationLogService;
import com.gimi.cloud.jimi.dao.dao.homePage.ColumnDao;
import com.gimi.cloud.jimi.dao.dao.homePage.MajorAdDao;
import com.gimi.cloud.jimi.dao.dao.product.ProductDao;
import com.gimi.cloud.jimi.dao.dao.product.ProductStatusDao;
import com.gimi.cloud.jimi.dao.myMapper.core.query.QueryParam;
import com.gimi.cloud.jimi.dto.app.ColumnProdDTO;
import com.gimi.cloud.jimi.dto.app.MajorAdDTO;
import com.gimi.cloud.jimi.dto.base.BaseDTO;
import com.gimi.cloud.jimi.dto.product.ProductDto;
import com.gimi.cloud.jimi.dto.product.ProductStatusDTO;
import com.gimi.cloud.jimi.entity.app.ColumnEntity;
import com.gimi.cloud.jimi.entity.app.MajorAdEntity;
import com.gimi.cloud.jimi.manage.service.app.MajorAdService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @auther loongs
 * @date 2017/12/29  13:13
 */
@Service
public class MajorAdServiceImpl implements MajorAdService {
    private static Logger logger = LoggerFactory.getLogger(MajorAdServiceImpl.class);
    private MajorAdDao majorAdDao;
    private ColumnDao columnDao;
    private ProductDao productDao;
    private ProductStatusDao productStatusDao;
    private JmOperationLogService jmOperationLogService;

    @Autowired
    public MajorAdServiceImpl(MajorAdDao majorAdDao, JmOperationLogService jmOperationLogService, ProductStatusDao productStatusDao,
                              ColumnDao columnDao, ProductDao productDao) {
        this.majorAdDao = majorAdDao;
        this.jmOperationLogService = jmOperationLogService;
        this.columnDao = columnDao;
        this.productDao = productDao;
        this.productStatusDao = productStatusDao;
    }

    @Override
    public Page<MajorAdDTO> getMajorAdList(MajorAdDTO majorAdDTO) {
        PageHelper.startPage(majorAdDTO.getCurrentPage(), majorAdDTO.getPageSize());
        long startTime = System.currentTimeMillis();
        List<MajorAdDTO> result = majorAdDao.queryPageList(majorAdDTO);
        if (result != null) {
            Date imgDate = AliOSSUtil.getNoEffictDateByDay(1);
            for (MajorAdDTO dto : result) {
                dto.setImgUrl(AliOSSUtil.getFileUrl(dto.getImgUrl(), imgDate));
            }
        }
        long endTime = System.currentTimeMillis();
        logger.info("后台获取主页广告时间：" + (endTime - startTime) + "ms");
        Page<MajorAdDTO> page = new Page(new PageInfo<>(result));
        return page;
    }

    @Override
    public Map<String, Object> majorAdRelyColumnProd(MajorAdDTO majorAdDTO) {
        Map<String, Object> data = new HashMap<>();
        PageHelper.startPage(majorAdDTO.getCurrentPage(), majorAdDTO.getPageSize());
        if (!StringUtil.isBlank(majorAdDTO.getProdName())) {
            majorAdDTO.setProdName("%" + majorAdDTO.getProdName() + "%");
        }
        String sql = " SELECT prod_id ,prod_name ,prod_adword , prod_price,prod_min_price,prod_max_price FROM ec_product  where 1=1 and prod_name like :prodName  ";
        QueryParam queryParam = new QueryParam();
        queryParam.setSql(sql);
        queryParam.setParamObject(majorAdDTO);
        List<ColumnProdDTO> results = productDao.majorAdRelyColumnProdPage(queryParam);
        PageInfo<ColumnProdDTO> page = new PageInfo<>(results);
        data.put("productDtoList", page);
        return data;
    }

    @Override
    public Map<String, Object> majorAdRelyColumn(MajorAdDTO majorAdDTO){
        Map<String, Object> data = new HashMap<>();
        Example example = new Example(ColumnEntity.class);
        example.createCriteria().andCondition("column_status=", 1);
        List<ColumnEntity> columnEntityList = columnDao.selectByExample(example);
        data.put("columnEntityList", columnEntityList);
        return data;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public boolean addMajorAd(MajorAdDTO majorAdDTO) {
        MajorAdEntity majorAdEntity = majorAdDao.selectMajorAdEntityByadName(majorAdDTO);
        if (majorAdEntity != null) {
            throw new MsgException(ResponseCodeEnum.MAJORAD_IS_EXIT);
        }
        MajorAdEntity majorAdEntityTemp = new MajorAdEntity();
        BeanUtils.copyProperties(majorAdDTO, majorAdEntityTemp);

        majorAdEntityTemp.setPageId(1);//强行设置pageId为0
        majorAdEntityTemp.setAdName(majorAdDTO.getTitle());
        majorAdEntityTemp.setSubTitle(majorAdDTO.getTitle());

        //初始化的广告位待发布状态
        majorAdEntityTemp.setImgUrl(AliOSSUtil.getFilePath(majorAdEntityTemp.getImgUrl()));
        majorAdEntityTemp.setAdStatus(CommonEnume.AdStatus.valueOf("c").toString());
        Integer flag = majorAdDao.insertSelective(majorAdEntityTemp);
        if (flag > 0) {
            //添加操作日志
            BaseDTO baseDTO = new BaseDTO();
            BeanUtils.copyProperties(majorAdDTO, baseDTO);
            jmOperationLogService.insertAddLog(baseDTO, majorAdDTO.getId() + "", "addMajorAd", "jimi_major_ad", "添加首页广告");
            return true;
        }
        return false;
    }

    @Override
    public MajorAdEntity gotoEditMajorAd(MajorAdDTO majorAdDTO) {
        MajorAdEntity majorAdEntity = majorAdDao.selectByPrimaryKey(majorAdDTO.getId());
        majorAdEntity.setImgUrl(AliOSSUtil.getFileUrl(majorAdEntity.getImgUrl(), AliOSSUtil.getNoEffictDateByDay(1)));
        //如果说广告类型为1的话，需要将商品名字返回给前段
        if (majorAdEntity.getAdClass() == 1) {
            ProductDto productDto = productDao.findByProdId(majorAdEntity.getAdObject());
            if (productDto != null) {
                majorAdEntity.setProdName(productDto.getProdName());
            } else {
                majorAdEntity.setProdName("");
            }
        }
        if (majorAdEntity.getAdClass() == 2) {
            ColumnEntity columnEntity = columnDao.selectByPrimaryKey(majorAdEntity.getAdObject());
            if (columnEntity != null) {
                majorAdEntity.setColumnName(columnEntity.getColumnName());
            } else {
                majorAdEntity.setColumnName("");
            }
        }
        //添加操作日志
        jmOperationLogService.insertQueryLog(new BaseDTO(), "gotoEditMajorAd", "jimi_major_ad", majorAdDTO.getId() + "", "转跳到指定首页广告界面");
        return majorAdEntity;
    }

    @Override
    public boolean editMajorAd(MajorAdDTO majorAdDTO) {
        //校验，如果已存在的广告名不能再添加或者修改成为此广告
        MajorAdEntity majorAdEntityTemp = majorAdDao.selectMajorAdEntityByadName(majorAdDTO);
        if (majorAdEntityTemp != null && majorAdEntityTemp.getId().intValue() != majorAdDTO.getId().intValue()) {
            throw new MsgException(ResponseCodeEnum.MAJORAD_IS_EXIT);
        }

        MajorAdEntity majorAdEntity = new MajorAdEntity();
        BeanUtils.copyProperties(majorAdDTO, majorAdEntity);

        majorAdEntityTemp.setPageId(1);//强行设置pageId为0
        majorAdEntityTemp.setAdName(majorAdDTO.getTitle());
        majorAdEntityTemp.setSubTitle(majorAdDTO.getTitle());

        //如果广告类型是2的话，adObject应该放栏目id
        //1放栏目下商品id
        //3 adObject 字段为空，但是targetUrl字段需要链接地址
        if (2 == majorAdEntity.getAdClass() || 1 == majorAdEntity.getAdClass()) {
            majorAdEntity.setTargetUrl("");
        }
        if (3 == majorAdEntity.getAdClass()) {
            majorAdEntity.setAdObject("");
        }
        majorAdEntity.setModifyTime(new Date());
        majorAdEntity.setImgUrl(AliOSSUtil.getFilePath(majorAdEntity.getImgUrl()));
        Integer flag = majorAdDao.updateByPrimaryKey(majorAdEntity);
        if (flag > 0) {
            //添加操作日志
            BaseDTO baseDTO = new BaseDTO();
            BeanUtils.copyProperties(majorAdDTO, baseDTO);
            jmOperationLogService.insertUpdateLog(baseDTO, "editMajorAd", "jimi_major_ad", majorAdEntity.getId() + "", "编辑指定首页广告");
            return true;
        }
        return false;
    }

    @Override
    public boolean deleteMajorAd(MajorAdDTO majorAdDTO) throws MsgException {
        MajorAdEntity majorAdEntity = majorAdDao.selectByPrimaryKey(majorAdDTO.getId());
        if (majorAdEntity == null) {
            throw new MsgException(ResponseCodeEnum.MAJORAD_IS_NOT_EXIT);
        }
        //d代表已经发布，不能直接删除发布的广告，如果要删除需先下架再删除
        if ((CommonEnume.AdStatus.valueOf("d").toString()).equals(majorAdEntity.getAdStatus())) {
            throw new MsgException(ResponseCodeEnum.AD_IS_PUBLISHED_CANNOT_DEL);
        }
        Integer flag = majorAdDao.deleteByPrimaryKey(majorAdEntity);
        if (flag > 0) {
            //添加操作日志
            jmOperationLogService.insertDeleteLog(majorAdDTO.getAddUid(), "deleteMajorAd", "jimi_major_ad", majorAdDTO.getId() + "", "删除指定首页广告");
            return true;
        }
        return false;
    }

    @Override
    public boolean underMajorAd(MajorAdDTO majorAdDTO) throws MsgException {
        MajorAdEntity majorAdEntity = majorAdDao.selectByPrimaryKey(majorAdDTO.getId());
        //处于已发布的主页广告才能撤下
        if (majorAdEntity == null || !(CommonEnume.AdStatus.valueOf("d").toString()).equals(majorAdEntity.getAdStatus())) {
            throw new MsgException(ResponseCodeEnum.MAJORAD_IS_NOT_EXIT_OR_PUBLISH);
        }
        majorAdEntity.setAdStatus(CommonEnume.AdStatus.valueOf("e").toString());
        majorAdEntity.setModifyTime(new Date());
        Integer flag = majorAdDao.updateByPrimaryKey(majorAdEntity);
        if (flag > 0) {
            //添加操作日志
            BaseDTO baseDTO = new BaseDTO();
            BeanUtils.copyProperties(majorAdDTO, baseDTO);
            jmOperationLogService.insertUpdateLog(baseDTO, "underMajorAd", "jimi_major_ad", majorAdDTO.getId() + "", "撤下首页广告");
            return true;
        }
        return false;
    }

    @Override
    public boolean publishMajorAd(MajorAdDTO majorAdDTO) throws MsgException {
        MajorAdEntity majorAdEntity = majorAdDao.selectByPrimaryKey(majorAdDTO.getId());
        //处于待发布和撤下的广告可以发布
        if (majorAdEntity == null || (!CommonEnume.AdStatus.valueOf("c").toString().equals(majorAdEntity.getAdStatus())
                && !CommonEnume.AdStatus.valueOf("e").toString().equals(majorAdEntity.getAdStatus()))) {
            throw new MsgException(ResponseCodeEnum.MAJORAD_IS_NOT_EXIT_OR_LOAODING_OR_UNDER);
        }
        ProductStatusDTO productStatusDTO = null;
        //如果广告是商品
        //判断商品是否上架，商品没上架，广告不能上架
        if (1 == majorAdEntity.getAdClass()) {
            productStatusDTO = productStatusDao.getProductStats(majorAdEntity.getAdObject());
            if (productStatusDTO == null || 1 != productStatusDTO.getProdStatus()) {
                throw new MsgException(ResponseCodeEnum.FAILURE, "广告下的商品未上架，广告不能上架，请确认重试！");
            }
        }
        majorAdEntity.setAdStatus(CommonEnume.AdStatus.valueOf("d").toString());
        majorAdEntity.setPublishMan(majorAdDTO.getAddUid());
        majorAdEntity.setPublishTime(majorAdDTO.getPublishTime());
        majorAdEntity.setEndTime(majorAdDTO.getEndTime());
        majorAdEntity.setModifyTime(new Date());
        Integer flag = majorAdDao.updateByPrimaryKey(majorAdEntity);
        if (flag > 0) {
            //添加操作日志
            BaseDTO baseDTO = new BaseDTO();
            BeanUtils.copyProperties(majorAdDTO, baseDTO);
            jmOperationLogService.insertUpdateLog(baseDTO, "publishMajorAd", "jimi_major_ad", majorAdDTO.getId() + "", "发布首页广告");
            return true;
        }
        return false;
    }
}
